<template>
  <div :class="{'mobile-detail-wrap':showMobilePage}">
    <div class="arrears-detail-container no-margin mobile-radius">
      <template v-if="!permissionDenied">
        <ProgressStep v-if="!showMobilePage" :mode="2" :step-list="stepList" :order-status="stepActiveId" :is-show-correct="false" :is-expedited="detailInfo.isExpedited"/>
        <explanation :explanation="explanationObj" :countdown="true" @queryProcessData="queryProcessData" />
        <div v-loading="infoLoading" class="arrears-detail-content small-padding">
          <el-image v-if="isRevoke" :src="revokeImg" class="revoke-img"/>
          <div style="margin-bottom: 20px;">
            <SectionTitle title="基础信息" style="margin:0 0 10px 0"/>
            <el-form
              :class="{'mobile-el-form': showMobilePage}"
              :label-position="showMobilePage?'left':'right'"
              label-width="105px"
              class="abandon-form height55">
              <el-row :gutter="20" :class="{'dividing': !showMobilePage}">
                <el-col :span="12">
                  <el-form-item label="审批单号:">
                    <ToolTip :content="detailInfo.approvalNo" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="创建时间:">
                    <span v-if="detailInfo.createTime">{{ detailInfo.createTime | format('YYYY/MM/DD HH:mm') }}</span>
                    <span v-else>--</span>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="创建人:">
                    <CheckUserInfo v-if="detailInfo.creator" :label="detailInfo.creator" :user-id="detailInfo.creatorId" />
                    <div v-else>--</div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="所属部门:">
                    <ToolTip :content="detailInfo.department" />
                  </el-form-item>
                </el-col>
              </el-row>
              <SectionTitle title="转交信息" style="margin: 16px 0;" />
              <el-row :gutter="20" :class="{'dividing': !showMobilePage}">
                <el-col :span="12">
                  <el-form-item label="转交人:">
                    <CheckUserInfo v-if="detailInfo.passer" :label="detailInfo.passer" :user-id="detailInfo.passerId" />
                    <div v-else>--</div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="被转交人:">
                    <CheckUserInfo v-if="detailInfo.transferee" :label="detailInfo.transferee" :user-id="detailInfo.transfereeId" />
                    <div v-else>--</div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="转交欠款(元):">
                    <PriceColumn :real-val="detailInfo.amount" :price="detailInfo.amount / 100" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="转交说明:">
                    <ToolTip :content="detailInfo.remark" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </div>
        <ExamineAndApprove
          ref="examineAndApproveRef"
          :disabled="infoLoading"
          :process-id="processId"
          :main-id="arrearsTransferId"
          :version="version"
          :get-comments-api="getArrearsTransferComments"
          :comment-add-api="addArrearsTransferComment"
          :process-revocation-api="revokeArrearsTransferProcess"
          :process-recall-api="recallArrearsTransferProcess"
          :process-audit-api="auditArrearsTransferProcess"
          :create-user="createUser"
          :business-type="BUSINESS_TYPE.ARREARS_TRANSFER"
          :process-type="PROCESS_TYPE.ARREARS_TRANSFER"
          :audit-schedule-data="auditScheduleData"
          :senders="senders"
          :default-aduitor-list="[{id: detailInfo.creatorId, userName: detailInfo.creator}]"
          :approval-module-type="APPROVAL_MODULE_TYPE.ARREARS_TRANSFER"
          :show-print="true"
          :print-data="detailInfo"
          redirect-url="/businessPage/arrearsTransferDetail"
          detail-page-router-name="arrearsTransferDetail"
          edit-page-router-name="arrearsTransferEdit"
          @toBack="toBack"
          @setProcessData="setProcessData"
          @getAuditSchedule="getAuditSchedule"
          @queryProcessData="queryProcessData"
          @handlePressSend="handlePressSend"
          @handleCreateNew="handleCreateNew"
          @handleSendMsg="handleSendMsg"
          @handleSender="handleSender"
          @handleModify="handleModify('arrearsTransferEdit',{id: arrearsTransferId},{remodifyId: processId})"
          @getHistoryDetail="getHistoryDetail"
          @setCurrentVersion="setCurrentVersion"
          @freshDetail="queryInfo"
          @handleCancelPress="handleCancelPress"
        />
        <ding-ding-dialog
          ref="pressSendDialogRef"
          :btn1="'确认加急'"
          :btn2="'取消'"
          :show-send-checkbox="false"
          :select-with-user-load="false"
          :default-list="pressDefaultList"
          redirect-url="/businessPage/arrearsTransferDetail"
          summary-title="加急原因"
          title="催办通知"
          @handelOK="toSend" />
      </template>
      <DeniedPlaceholder v-else />
    </div>
  </div>
</template>
<script>
// 组件
import ListTab from '@/components/ListTab';
import ProgressStep from '@/components/CreateOrder/orderDetail/step';
import SectionTitle from '@/components/Title';
import explanation from '@/components/Common/explanation';
import ExamineAndApprove from '@/components/Common/ExamineAndApprove';
// 工具函数
import { mapState } from 'vuex';
import { PROGRESS_STEP } from '@/utils/const/energy';
import { hasRouteAuth } from '@/utils/permission';
import { BUSINESS_TYPE, PROCESS_TYPE } from '@/utils/const/process';
import { format } from '@/filters/date';
import { APPROVAL_MODULE_TYPE } from '@/utils/const';
// API
import {
  getArrearsTransferDetail,
  getArrearsTransferComments,
  addArrearsTransferComment,
  revokeArrearsTransferProcess,
  recallArrearsTransferProcess,
  auditArrearsTransferProcess
} from '@/api/arrearsTransfer';
import schedule from '@/mixins/schedule';
import revokeImg from '@/assets/auditProcess/process_status_3.png';

export default {
  components: {
    ListTab, ProgressStep, SectionTitle,
    explanation, ExamineAndApprove
  },
  filters: { format },
  mixins: [schedule],
  data() {
    return {
      APPROVAL_MODULE_TYPE,
      revokeImg,
      BUSINESS_TYPE, PROCESS_TYPE,
      processId: '', // 流程id
      detailInfo: {},
      infoLoading: false,
      permissionDenied: false, // 详情页是否可查看
      PROGRESS_STEP,
      // api
      revokeArrearsTransferProcess,
      addArrearsTransferComment,
      getArrearsTransferComments,
      recallArrearsTransferProcess,
      auditArrearsTransferProcess,
      stepActiveId: PROGRESS_STEP.PENDING,
      isRevoke: false,
      arrearsTransferId: '', // 借款单id
      accountInfo: [],
      processData: {
        list: []
      }
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    stepList() {
      return [
        { name: '待提交', id: PROGRESS_STEP.PENDING },
        { name: '审批中', id: PROGRESS_STEP.UNDER_REVIEW },
        { name: '已完成', id: PROGRESS_STEP.FINISHED }
      ];
    },
    createUser() {
      let user = { id: this.detailInfo.creatorId, userName: this.detailInfo.creator };
      if (this.userInfo.id === this.detailInfo.creatorId) {
        user = this.userInfo;
      }
      return user;
    },
    isApprover() { // 是否为当前节点审批人
      const processList = this.processData.list;
      if (!processList || processList.length === 0) return false;
      let item = null;
      // nodeStatus 节点状态: 0:结束 1:进行中 2:未审批
      for (let i = 0; i < processList.length; i++) {
        if (!item && processList[i].nodeStatus === 1) {
          item = processList[i];
          break;
        }
      }
      if (!item || item.length === 0) return false;
      let userList = [];
      item.items.forEach(i => {
        userList = userList.concat(i.users);
      });
      return userList.some(i => i.id === this.userInfo.id);
    },
    canEdit() {
      return this.isApprover && this.detailInfo.hasEditEvent && this.isCurrentVersion;
    }
  },
  created() {
    this.initData();
  },
  mounted() {
    if (this.$route.query.openComment) {
      this.$refs['examineAndApproveRef'].isShowProcess = true;
    }
  },
  methods: {
    hasRouteAuth,
    initData() {
      this.initRouteData();
      this.queryProcessData(); // 流程数据
    },
    initRouteData() {
      this.arrearsTransferId = this.$route.query.id;
      this.processId = this.$route.query.processId;
      if (!this.arrearsTransferId || !this.processId) {
        this.$message.warning('无法获取ID');
        const timer = setTimeout(() => {
          this.$router.back();
          clearTimeout(timer);
        }, 1500);
      }
    },
    setProcessData(processData) {
      this.processData = processData;
    },
    // 获取基本信息
    queryInfo() {
      this.infoLoading = true;
      getArrearsTransferDetail(this.arrearsTransferId).then(res => {
        this.handleProcessCheck(res.data.processId);
        this.handleDetailData(res);
      }).catch(err => {
        if (err.code === 403) {
          this.permissionDenied = true;
        }
        this.infoLoading = false;
      });
    },
    // 处理详情接口返回的数据
    handleDetailData(res) {
      this.infoLoading = false;
      if (res.code === 200) {
        this.commentCount = res.data.commentCount;
        if (res.data.processStatus === 3) { // 3为撤销
          this.stepActiveId = PROGRESS_STEP.PENDING;
          this.isRevoke = true;
        } else {
          this.stepActiveId = res.data.processStatus;
          this.isRevoke = false;
        }
        this.accountInfo = res.data.accountInfo;
        this.detailInfo = res.data;
      }
    },
    queryProcessData() {
      this.queryInfo();
      this.getAuditSchedule();
      this.$nextTick(() => {
        this.$refs.examineAndApproveRef && this.$refs.examineAndApproveRef.getProcessList();
      });
    },
    toBack() {
      if (this.$route.query.fromTodo) {
        this.$router.go(-1);
      } else {
        this.$router.push({ name: 'arrearsTransfer' });
      }
    },
    getAuditSchedule() {
      this.requestAuditSchedule(this.processId);
    },
    handleCreateNew() {
      const routeUrl = this.$router.resolve({
        name: 'arrearsTransferEdit',
        params: { id: this.arrearsTransferId },
        query: { reapplyId: this.processId, createNew: 1 }
      });
      window.open(routeUrl.href, '_blank');
    }
  }
};
</script>
<style lang="scss" scoped>
.arrears-detail-container{
  margin: 16px 16px 0 16px;
  background-color: #fff;
  padding-bottom: 55px;
  min-height: calc(100vh - 64px);
  .arrears-detail-content{
    position: relative;
    padding: 16px 24px 56px;
  }
  &::v-deep {
    .dividing{
      .el-col {
        padding-right: 0 !important;
        .el-form-item__content {
          border-right: 1px solid #EBEEFD;
        }
        &:nth-child(2n) {
          .el-form-item__content {
            border-right: none;
          }
        }
        &:last-child {
          .el-form-item__content {
            border-right: none;
          }
        }
      }
      .el-col:nth-child(even) {
        padding-left: 0 !important;
      }
    }
    .explanation-container{
      .explanation{
        padding-left: 32px!important;
      }
    }
  }
  .revoke-img{
    position: absolute;
    width: 80px;
    height: 80px;
    right: 56px;
    top: 33px;
    z-index: 999;
  }
}
::v-deep .el-drawer {
  min-width: 300px;
}
::v-deep .el-form-item__label {
  color: #999;
}
::v-deep .el-form-item {
  margin-bottom: 0 !important;
}
::v-deep .explanation {
  margin-bottom: 0;
}
</style>
